package com.minis.aop;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * JdkDynamicAopProxy 是 AopProxy 的一种实现方式
 */
public class JdkDynamicAopProxy implements AopProxy, InvocationHandler {
    Object target;
//    Advisor advisor;
    PointcutAdvisor advisor;
    public JdkDynamicAopProxy(Object target, PointcutAdvisor advisor) {
        this.target = target;
        this.advisor = advisor;
    }

    // 动态代理
    @Override
    public Object getProxy() {
        Object obj = Proxy.newProxyInstance(JdkDynamicAopProxy.class.getClassLoader(), target.getClass().getInterfaces(), this);
        return obj;
    }

    // 动态添加增强逻辑
    // 1 先拿到 Advisor 里面的 Interceptor
    // 2 然后把正常的 method 调用包装成 ReflectiveMethodInvocation
    // 3 最后调用 interceptor.invoke(invocation)
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Class<?> targetClass = (target != null ? target.getClass() : null);
//      if (method.getName().equals("doAction"))
        if (this.advisor.getPointcut().getMethodMatcher().matches(method, targetClass)) {
            if (this.advisor == null) {
                System.out.println("advisor 为空");
            }
            MethodInterceptor interceptor = this.advisor.getMethodInterceptor();
            MethodInvocation  invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass);
//            System.out.println("-----before call real object, dynamic proxy........");
//            return method.invoke(target, args);
            return interceptor.invoke(invocation);
        }
        return null;
    }
}
